package com.kpijavatraining.module.utils;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.kpijavatraining.module.User;

public class Checker {

	private Node user;
	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document document;
	private NodeList list;
	
	public Checker() throws ParserConfigurationException, SAXException, IOException{
		factory = DocumentBuilderFactory.newInstance();
		builder = factory.newDocumentBuilder();
		document = builder.parse("Users//Users.xml");
		list = document.getElementsByTagName("user");
	}
		
	public boolean identification(String login){
		for(int i = 0 ; i < list.getLength(); i++){
			NamedNodeMap attrs = list.item(i).getAttributes();
			if(attrs.getNamedItem("login").getNodeValue().equals(login)){
				user = list.item(i);		
				return true;	
			}
		}
		return false;
	}
	
	public boolean authenticationIs(String login, String password) throws IOException{
		if(!identification(login)){
			return false;
		}
		String userLogin = user.getAttributes().getNamedItem("login").getNodeValue();
		String userPassword = user.getAttributes().getNamedItem("password").getNodeValue();
		if(userLogin.equals(login) && userPassword.equals(password)){
			return true;
		}
		return false;
	}
	
	public boolean hasUncompleteTest(User user){
		File file = new File(user.toString()+".ucl");
		return file.exists();
	}
	
	public User getUser(){
		String login = user.getAttributes().getNamedItem("login").getNodeValue();
		String group = user.getAttributes().getNamedItem("group").getNodeValue();
		return new User(login,group);
	}	
}
